import 'package:chat_ai/src/components/session_config_widget.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CreateSession extends StatefulWidget {
  const CreateSession({super.key});

  @override
  State<StatefulWidget> createState() => _CreateSessionState();
}

class _CreateSessionState extends State<CreateSession> {
  final _formKey = GlobalKey<FormState>();
  final _nameInputController = TextEditingController();
  final _hostInputControllers = List.generate(
    4,
    (index) => TextEditingController(),
  );
  final _portInputController = TextEditingController();
  late final SharedPreferences _prefs;

  @override
  void initState() {
    super.initState();
    _initState();
  }

  void _initState() async {
    _prefs = await SharedPreferences.getInstance();
  }

  @override
  void dispose() {
    super.dispose();
    _nameInputController.dispose();
    for (int iter in Iterable.generate(4)) {
      _hostInputControllers[iter].dispose();
    }
    _portInputController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("新建会话"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: SessionConfigWidget(
          formKey: _formKey,
          nameInputController: _nameInputController,
          hostInputControllers: _hostInputControllers,
          portInputController: _portInputController,
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        child: ElevatedButton(
          child: const Text("保存会话"),
          onPressed: () {
            if (!_formKey.currentState!.validate()) return;
            List<String> sessionNames =
                _prefs.getStringList("sessionNames") ?? [];
            if (sessionNames.contains(_nameInputController.text)) {
              showDialog(
                context: context,
                builder: (context) => const AlertDialog(
                  title: Text("该名称已被占用"),
                ),
              );
              return;
            }
            sessionNames.add(_nameInputController.text);
            _prefs.setStringList("sessionNames", sessionNames);
            _prefs.setString(
              "${_nameInputController.text}.host",
              _hostInputControllers
                  .map((controller) => controller.text)
                  .join("."),
            );
            _prefs.setInt(
              "${_nameInputController.text}.port",
              int.parse(_portInputController.text),
            );
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}
